<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\ClothSizeRequest;
use App\Models\V1\ClotheSize;
use App\Models\V1\NewArrival;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;

class ClothSizeController extends Controller
{
    /**
     * 获取校服尺码
     *
     * @param Request $request
     */
    public function postSizeIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];
        // 获取符合查询条件的班级数据
        $code = $request->get('code');
        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('arrival_code');

        // 获取符合查询条件的班级数据
        $data = $this->getClothSizesByCode($currentPage, $rows, $keywords,$code);
        if (!$data->isEmpty()) {
            $formatList = array();
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['height_low'] = $item['height_low'];
                    $formatItem['height_high'] = $item['height_high'];
                    $formatItem['size'] = $item['size'];
                    $formatItem['cloth_length'] = $item['cloth_length'];
                    $formatItem['bust'] = $item['bust'];
                    $formatItem['arrival_code'] = $item['arrival_code'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }





    /****
     * @param ClothSizeRequest $request
     * @return array
     */
    public function deleteSizeData(ClothSizeRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校服尺寸代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCloth($request);

            // 删除校服尺寸信息
            $successFlag = $this->handleDeleteSize($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '校服尺寸代码[' . $request->input('code') . '],删除成功！';
            }
        }
        return $response;
    }


    /***
     * 更新table中代码
     * @param ClothSizeRequest $request
     * @return array
     */
    public function updateCellSizeData(ClothSizeRequest $request) {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校服尺寸代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCloth($request);

            // 更新部门信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '校服尺寸代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 新增尺码信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校服尺码[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['name'] = 'bail|required';
            $rules['cloth_code'] = 'bail|required';
            $rules['height_low'] = 'bail|required';
            $rules['height_high'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '校服尺码代码不能为空';
            $messages['name.required'] = '校服尺码名称不能为空';
            $messages['cloth_code.required'] = '校服代码不能为空';
            $messages['height_low.required'] = '最低适用身高不能为空';
            $messages['height_high.required'] = '最高适用身高不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '校服尺码[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }



    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新班级信息验证请求
     *
     * @param Request $request
     */
    private function validateCloth(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    /***
     * 根据校服代码获取校服尺寸
     * @param $code
     */
    private function getClothSizesByCode($page = 1, $rows, $keywords,$code) {
        if (!isset($keywords) || empty($keywords)) {
            $data = ClotheSize::where('cloth_code',$code)->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = ClotheSize::where('arrival_code', 'like', '%' . $keywords . '%')
                ->where('cloth_code',$code)
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }


    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /***
     * 删除校服尺码
     * @param Request $request
     * @param $bBatch
     * @return mixed
     */
    private function handleDeleteSize(Request $request, $bBatch)
    {
        $where = $request->input('code');
        $arrival_code = $request->input('arrival_code');
        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = ClotheSize::where(['code'=>$code,'arrival_code'=>$arrival_code])
                    ->delete();
            }
        } else { // 单条删除
            $rspObj = ClotheSize::where(['code'=>$where,'arrival_code'=>$arrival_code])
                ->delete();
        }

        return $rspObj;
    }

    /****
     * @param Request $request
     * @param $bCell 是否为单元格修改数据
     * @return mixed
     */
    public function handleUpdate(Request $request, $bCell) {
        $where = $request->input('code');
        $arrival_code = $request->input('arrival_code');
        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'name' => $request->input('name'),
                'cloth_code' => $request->input('cloth_code'),
                'height_low' => $request->input('height_low'),
                'height_high' => $request->input('height_high'),
                'size' => $request->input('size'),
                'cloth_length' => $request->input('cloth_length'),
                'bust' => $request->input('bust'),
            ];
        }

        $rspObj = ClotheSize::where('code', $where)
            ->where('arrival_code',$arrival_code)
            ->update($updateData);

        return $rspObj;
    }

    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request) {
        $arrival_code = $this->getArrivalCodes();
        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'name' => $request->input('name'),
            'cloth_code' => $request->input('cloth_code'),
            'height_low' => $request['height_low'],
            'height_high' => $request['height_high'],
            'size' => isset($request['size'])?$request->input('size'):'',
            'cloth_length' => isset($request['cloth_length'])?$request->input('cloth_length'):'',
            'bust' => isset($request['bust'])?$request->input('bust'):'',
            'arrival_code' => $arrival_code,
        ];
        $rspObj = ClotheSize::updateOrCreate(['code'=>$request->input('code'),'arrival_code'=>$arrival_code],$insertData);
        return $rspObj;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }


}
